package com.example.demo.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;

public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor {

    private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment,
                                       SpringApplication application) {
        String[] activeProfiles = environment.getActiveProfiles();
        //通配符来读取
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            for(String activeProfile:activeProfiles) {
                Resource[] resources = resolver.getResources(activeProfile + "/*.yml");
                for(Resource resource:resources){
                    PropertySource<?> propertySource = loadYaml(resource.getFilename(),resource);
                    environment.getPropertySources().addLast(propertySource);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private PropertySource<?> loadYaml(String name,Resource path) {
        if (!path.exists()) {
            throw new IllegalArgumentException("Resource " + path + " does not exist");
        }
        try {
            return this.loader.load(name, path).get(0);
        }
        catch (IOException ex) {
            throw new IllegalStateException(
                    "Failed to load yaml configuration from " + path, ex);
        }
    }
}
